import axios from 'axios';
import { BASE_URL } from '@/constants/api';
import router from '@/router';

const req = axios.create({
  baseURL: BASE_URL,
});

// 请求拦截
req.interceptors.request.use((config) => {
  config.headers = {
    ...config.headers,
    Authorization: localStorage.getItem('TOKEN') ?? '',
    contentType: 'application/x-www-form-urlencoded',
  };
  return config;
});

// 响应拦截
req.interceptors.response.use(
  // 成功回调
  (res) => res,
  // 失败回调
  (err) => {
    switch (err.response.status) {
    case 401:
      router.push('/login');
      break;

    default:
      break;
    }
    return Promise.reject(err);
  },
);

export default req;
